package com.imooc.business.processor;

import com.imooc.business.OrganBusiness;
import com.imooc.business.builder.RequestBuilder;
import com.imooc.business.core.DataProcess;
import com.imooc.business.facade.model.Organ;
import com.imooc.module.collect.enums.DimensionEnum;
import com.imooc.module.collect.enums.PeriodEnum;
import com.imooc.module.collect.enums.RuleTypeEnum;
import com.imooc.module.collect.request.ParamsRequest;
import com.imooc.module.collect.request.RequestPeriod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author Tim
 * @Description: 默认数据处理器，组装数据处理的request
 * @Version 1.0
 */
@Slf4j
@Component
public class DefaultRequestProcessor {

    private final OrganBusiness organBusiness;
    private final DataProcess dataProcess;

    public DefaultRequestProcessor(OrganBusiness organBusiness, DataProcess dataProcess) {
        this.organBusiness = organBusiness;
        this.dataProcess = dataProcess;
    }

    /**
     * 数据处理入口
     *
     * @param businessId
     * @param groupIds
     * @param requestDate
     */
    @Async(value = "dataProcessExecutor")
    public void process(String businessId, List<String> groupIds, Date requestDate) {
        log.info("process start, businessId:{}, groupIds:{}, requestDate:{}", businessId, groupIds, requestDate);
        RequestPeriod requestPeriod = RequestBuilder.buildPeriod(PeriodEnum.DAY, requestDate);
        List<Organ> requestOrgans = organBusiness.getRequestOrgans(businessId, groupIds, requestPeriod.getStartTime(), requestPeriod.getEndTime());

        requestOrgans.parallelStream().forEach(organ -> {
            ParamsRequest.DimensionParameter dimensionParameter = RequestBuilder.buildDimension(organ, DimensionEnum.USER);
            ParamsRequest request = RequestBuilder.buildParamsRequest(businessId, dimensionParameter, requestPeriod);
            request.setRuleTypeEnum(RuleTypeEnum.COLLECT);
            dataProcess.process(request);
        });
        log.info("process finish, businessId:{}", businessId);
    }
}
